package com.smartlazy.delay.queue.client.web;

import com.alibaba.fastjson.JSONObject;
import com.github.youzan.httpfetch.HttpApiConfiguration;
import com.github.youzan.httpfetch.HttpApiService;
import com.smartlazy.delay.queue.client.api.DelayQueueApi;
import com.smartlazy.delay.queue.client.bean.JobItem;
import com.smartlazy.delay.queue.client.bean.ReturnInfo;
import com.smartlazy.delay.queue.client.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author howe
 */
@Slf4j
@Controller
@RequestMapping("/")
public class TestController {

    /**
     * 添加job
     * @return
     */
    @RequestMapping(value = "/push", method = RequestMethod.POST)
    @ResponseBody
    public ReturnInfo<Boolean> push() {
        ReturnInfo<Boolean> ret = new ReturnInfo<Boolean>();
        try {
            HttpApiService httpApiService = new HttpApiService(new HttpApiConfiguration());
            httpApiService.init();
            DelayQueueApi delayQueueApi = httpApiService.getOrCreateService(DelayQueueApi.class);
            JobItem param = new JobItem();
            param.setTopic("订单延时");
            param.setDelay(30);
            param.setId(UUIDUtils.getShortUuid());
            param.setTimestamp(0);
            param.setTtr(10);
            param.setBody("id=1&name=测试");
            ReturnInfo<Boolean> responseVo = delayQueueApi.push(param);
            System.out.println(JSONObject.toJSONString(responseVo));
            return responseVo;
        } catch (Exception e) {
            ret.setErrorCode("500");
            ret.setErrorText("系统异常");
            ret.setReturnCode(2);
            log.error("系统异常", e);
        }
        return ret;
    }

    /**
     * 获取job
     * @return
     */
    @RequestMapping(value = "/pop", method = RequestMethod.POST)
    @ResponseBody
    public ReturnInfo pop() {
        ReturnInfo ret = new ReturnInfo();
        try {
            HttpApiService httpApiService = new HttpApiService(new HttpApiConfiguration());
            httpApiService.init();
            DelayQueueApi delayQueueApi = httpApiService.getOrCreateService(DelayQueueApi.class);
            ReturnInfo<JobItem> responseVo = delayQueueApi.pop("订单延时");
            System.out.println(JSONObject.toJSONString(responseVo));
            ret.setErrorCode("200");
            ret.setErrorText("成功");
            ret.setReturnCode(1);
        } catch (Exception e) {
            ret.setErrorCode("500");
            ret.setErrorText("系统异常");
            ret.setReturnCode(2);
            log.error("系统异常", e);
        }
        return ret;
    }
}
